package applicationAlibi;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import tables.*;

/**
 * Servlet implementation class ApplicationAlibi
 */
public class ApplicationAlibi extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final String TMP_DIR_PATH = "/tmp";
	private File tmpDir;
	private static final String DESTINATION_DIR_PATH = "/photoMembre";
	private File destinationDir;
	public static String cheminPhoto = "image/pub.jpg";
	public static String pseu = "";

	public void init(ServletConfig config) throws ServletException {

		super.init(config);
		tmpDir = new File(TMP_DIR_PATH);
		if (!tmpDir.isDirectory()) {
			throw new ServletException(TMP_DIR_PATH + " is not a directory");
		}

		 String realPath =
		 getServletContext().getRealPath(DESTINATION_DIR_PATH);
		// String realPath = "C:/Users/Amandine/Documents";
		destinationDir = new File(realPath);

		if (!destinationDir.isDirectory()) {
			throw new ServletException(DESTINATION_DIR_PATH
					+ " is not a directory");
		}
	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ApplicationAlibi() {
		super();
	}

	/**
	 * methode pour convertir un mois en son Ã©quivalent numÃ©rique
	 * 
	 * @param m
	 * @return numÃ©ro du mois
	 */
	public static int convert(String m) {
		int res = 0;
		if (m.equals("janvier"))
			res = 1;
		else if (m.equals("fevrier"))
			res = 2;
		else if (m.equals("mars"))
			res = 3;
		else if (m.equals("avril"))
			res = 4;
		else if (m.equals("mai"))
			res = 5;
		else if (m.equals("juin"))
			res = 6;
		else if (m.equals("juillet"))
			res = 7;
		else if (m.equals("aout"))
			res = 8;
		else if (m.equals("septembre"))
			res = 9;
		else if (m.equals("octobre"))
			res = 10;
		else if (m.equals("novembre"))
			res = 11;
		else if (m.equals("decembre"))
			res = 12;

		return res;
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String vC = request.getParameter("validerCreation");

		if (vC == null) {
			vC = "null";
		}

		// /////////////////////////////////////
		// creation de compte //
		// /////////////////////////////////////

		if (vC.equals("Valider")) {

			// on recupere les donnees
			// infos generales
			String nom = request.getParameter("nom");
			String prenom = request.getParameter("prenom");
			String pseudo = request.getParameter("pseudo");
			String jour = request.getParameter("jour");
			String mois = request.getParameter("mois");
			String an = request.getParameter("an");
			String sexe = request.getParameter("sexe");
			String adresse = request.getParameter("adresse");
			String ville = request.getParameter("ville");

			// contact
			String tel = request.getParameter("telephone");
			String email = request.getParameter("email");

			// infos personnelles
			String statut = request.getParameter("statut");
			String orientation = request.getParameter("orientation");
			String taille = request.getParameter("taille");
			String cheveux = request.getParameter("cheveux");
			String yeux = request.getParameter("yeux");

			// info compte (login=pseudo)
			String motDePasse = request.getParameter("motDePasse");
			String motDePasse2 = request.getParameter("motDePasse2");

			// si motDePasse != motDePasse2 il faut afficher un message ---> jsp
			// :-(
			if (!motDePasse.equals(motDePasse2)) {
				request.setAttribute("fauxMotDePasse", "faux");
				// on retransmet les infos pour que l'utilisateur n'est pas
				// besoin de tout retaper
				// infos generales
				request.setAttribute("nom", nom);
				request.setAttribute("prenom", prenom);
				request.setAttribute("pseudo", pseudo);
				request.setAttribute("jour", jour);
				request.setAttribute("mois", mois);
				request.setAttribute("an", an);
				request.setAttribute("sexe", sexe);
				request.setAttribute("adresse", adresse);
				request.setAttribute("ville", ville);

				// contact
				request.setAttribute("telephone", tel);
				request.setAttribute("email", email);

				// infos personnelles
				request.setAttribute("statut", statut);
				request.setAttribute("orientation", orientation);
				request.setAttribute("taille", taille);
				request.setAttribute("cheveux", cheveux);
				request.setAttribute("yeux", yeux);

				request.getRequestDispatcher("creationCompte.jsp").forward(
						request, response);
			} else {
				boolean b = false;
				try {
					b = JdbcUtilisateur.pseudoLibre(pseudo);
				} catch (Exception e) {
					System.out
							.println("_X__ erreur pseudoLibre d'un utilisateur");
					request.getRequestDispatcher("chargementPhoto.jsp")
							.forward(request, response);
				}
				// on cree le compte dans la base de donnees
				if (b) {
					try {
						JdbcUtilisateur.addMembre(pseudo, nom, prenom, ville,
								adresse, convgen(sexe), an + "-"
										+ ((Integer) convert(mois)).toString()
										+ "-" + jour, orientation, statut,
								motDePasse, email, tel, "",
								Integer.parseInt(taille), cheveux, yeux);
					} catch (Exception e) {
						System.out.println("_X__ erreur add d'un utilisateur");
						request.getRequestDispatcher("creationCompte.jsp")
								.forward(request, response);
					}

					// redirection vers la page pour le chargement de la photo
					pseu = pseudo;
					request.getRequestDispatcher("chargementPhoto.jsp")
							.forward(request, response);

				}
			}
		}

	}

	public static int convgen(String s) {
		if (s.equals("femme"))
			return 2;
		else
			return 1;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");

		if (ServletFileUpload.isMultipartContent(request)) {
			DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
			/*
			 * Set the size threshold, above which content will be stored on
			 * disk.
			 */
			fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
			/*
			 * Set the temporary directory to store the uploaded files of size
			 * above threshold.
			 */
			fileItemFactory.setRepository(tmpDir);

			ServletFileUpload uploadHandler = new ServletFileUpload(
					fileItemFactory);
			try {
				/*
				 * Parse the request
				 */
				@SuppressWarnings("rawtypes")
				List items = uploadHandler.parseRequest(request);
				@SuppressWarnings("rawtypes")
				Iterator itr = items.iterator();
				while (itr.hasNext()) {
					FileItem item = (FileItem) itr.next();
					/*
					 * Handle Form Fields.
					 */
					if (item.isFormField()) {
						// out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
					} else {
						/*
						 * Write file to the ultimate location.
						 */
						// cheminPhoto=destinationDir+"/"+item.getName();
						cheminPhoto = item.getName();

						File file = new File(DESTINATION_DIR_PATH,
								item.getName());
						item.write(file);
					}
				}
			} catch (Exception ex) {
				log("Error encountered while uploading file", ex);
			}

		}
		try {
			System.out.println("chemin photo : " + cheminPhoto);
			JdbcUtilisateur.maj_photo(pseu, cheminPhoto);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		request.getRequestDispatcher("finCreationCompte.jsp").forward(request,
				response);
	}

}
